package xgenerator.ui.swing.adapter;

import java.awt.Component;
import java.util.Vector;

import javax.swing.DefaultComboBoxModel;
import javax.swing.JComboBox;
import javax.swing.JOptionPane;
import javax.swing.event.PopupMenuEvent;
import javax.swing.event.PopupMenuListener;

import xgenerator.service.MetadataService;
import xgenerator.service.impl.MetadataServiceImpl;
import xgenerator.ui.swing.JGeneratorFrame;
import xgenerator.ui.swing.MetadataTable;
import xgenerator.util.StringUtils;

public class TableComboBoxPopupMenuListener implements PopupMenuListener {
	
	/**
	 * MetadataService
	 */
	private MetadataService metadataService;
	
	/**
	 * UI组件
	 */
	private Component ui;
	
	/**
	 * constructor
	 * @param ui
	 */
	public TableComboBoxPopupMenuListener(Component ui) {
		this.ui = ui;
		this.metadataService = new MetadataServiceImpl();
	}

	/**
	 * <p>
	 * Title：
	 * </p>
	 * @author <a href="mailto:shushanlee@msn.com">liss</a>
	 * @param e
	 * @see javax.swing.event.PopupMenuListener#popupMenuCanceled(javax.swing.event.PopupMenuEvent)
	 */
	public void popupMenuCanceled(PopupMenuEvent e) {

	}

	/**
	 * <p>
	 * Title：
	 * </p>
	 * @author <a href="mailto:shushanlee@msn.com">liss</a>
	 * @param e
	 * @see javax.swing.event.PopupMenuListener#popupMenuWillBecomeInvisible(javax.swing.event.PopupMenuEvent)
	 */
	public void popupMenuWillBecomeInvisible(PopupMenuEvent e) {
		
	}

	/**
	 * <p>
	 * Title：
	 * </p>
	 * @author <a href="mailto:shushanlee@msn.com">liss</a>
	 * @param e
	 * @see javax.swing.event.PopupMenuListener#popupMenuWillBecomeVisible(javax.swing.event.PopupMenuEvent)
	 */
	public void popupMenuWillBecomeVisible(PopupMenuEvent e) {
		try {
			MetadataTable metadataTable = (MetadataTable) ui;
			JGeneratorFrame jGeneratorFrame = (JGeneratorFrame) metadataTable.getParentComponent();
			JComboBox datasourceComboBox = jGeneratorFrame.getDataSourceComboBox();
			Object selectedItem = datasourceComboBox.getSelectedItem();
			String datasourceName = StringUtils.toString(selectedItem);
			System.out.println("datasourceName=" + datasourceName);
			
			Vector dataVector = metadataService.getTables(datasourceName);
			JComboBox tableComboBox = (JComboBox) e.getSource();
			tableComboBox.setModel(new DefaultComboBoxModel(dataVector));
		} catch (Exception ex) {
			JOptionPane.showMessageDialog(ui, ex.getMessage(), "错误", JOptionPane.ERROR_MESSAGE);
			ex.printStackTrace();
		}
	}

}
